package com.tg.app.activity.device.ui.cameraview;


import android.app.Activity;
import android.content.res.Configuration;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.appbase.custom.constant.CommonConstants;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.demo.view.BreathingLightView;
import com.demo.view.RecordAudioView;
import com.ns.yc.yccardviewlib.shadow.ShadowLayout;
import com.tange.module.camera.hub.CameraHub;
import com.tange.module.device.feature.DeviceFeature;
import com.tg.app.R;
import com.tg.app.activity.device.CameraViewActivity;
import com.tg.app.helper.ActivityHelper;
import com.tg.app.helper.CameraViewHelper;
import com.tg.app.helper.DeviceFeatureHelper;
import com.tg.app.view.ACCameraPlayerView;
import com.tg.app.view.MsgCenterToast;
import com.tg.app.widget.BottomSheetListDialog;
import com.tg.appcommon.android.TGApplicationBase;
import com.tg.appcommon.android.TGLog;
import com.tg.data.bean.DeviceItem;

import java.util.List;

public abstract class CameraLiveViewFragment extends CameraBaseFragment implements RecordAudioView.IRecordAudioListener {
    protected static final String EXT_DEVICE_FEATURE = "device_feature";
    private static final String TAG = "CameraPlayerView";
   
    protected BreathingLightView lightView;
    private RecordAudioView.IRecordAudioListener recordAudioListener;
    private boolean hasAudioPermission;
    protected DeviceFeature deviceFeature;
    protected RecordAudioView btnSpeaking, btnSpeakingLand;
    protected ImageView recordViewIcon;
    protected ShadowLayout recordViewShadowLayout;

    protected RelativeLayout relMicPhone;
    protected View layout;
    protected boolean isLandscape = false;
    protected View mPlayerResolutionLayout;

    public static Bundle newBundle(DeviceFeature deviceFeature, DeviceItem deviceItem) {
        Bundle args = new Bundle();
        args.putParcelable(EXT_DEVICE_FEATURE, deviceFeature);
        args.putParcelable(CommonConstants.EXT_DEVICE_ITEM, deviceItem);
        return args;
    }

    public void setRecordAudioListener(RecordAudioView.IRecordAudioListener recordAudioListener) {
        this.recordAudioListener = recordAudioListener;
    }


    @Override
    public void onResume() {
        super.onResume();
        TGLog.i(TAG, "onResume ");
        final CameraViewActivity cameraViewActivity = (CameraViewActivity) getActivity();
        assert cameraViewActivity != null;
        if (cameraViewActivity.getPlayerView().getMediaSync()!=null){
            cameraViewActivity.getPlayerView().getMediaSync().setFrameBufferMin(0);
        }

        if (mCamera != null) {
            if (mCamera.isConnected()) {
                setClicked(true);
                if (cameraViewActivity.isLocalConnect()&& (deviceFeature == null || TextUtils.isEmpty(deviceFeature.uuid))){
                    cameraViewActivity.getGetEnv();
                }
                setEnterSetupCMD();
            }
            cameraViewActivity.isMicrophoneClose();
            ActivityHelper.connectImpl(cameraViewActivity, mCamera, true);
        }
        if (mCamera != null) {
            if (mCamera.isConnected()) {
                setClicked(true);
            }
        }
        int orientation = getResources().getConfiguration().orientation;
        configurationView(orientation);
    }

   
    public void calculateVolume(short data) {
        if (lightView != null) {
            lightView.calculateVolume(data);
        }
    }

    public void setClicked(boolean enable) {
        boolean supportTalkBack = !DeviceFeatureHelper.isAec(deviceFeature);
        if (btnSpeaking != null) {
            btnSpeaking.setLongClickRecord(supportTalkBack);
            btnSpeaking.setClickable(enable);
            btnSpeaking.setEnabled(enable);
        }
        if (btnSpeakingLand!=null){
            btnSpeakingLand.setLongClickRecord(supportTalkBack);
            btnSpeakingLand.setClickable(enable);
            btnSpeakingLand.setEnabled(enable);
            if (!enable){
                btnSpeakingLand.stopRecordAudio();
            }
        }
        if (!enable) {
            if (lightView != null) {
                lightView.setVisibility(View.GONE);
            }
            recordAudioStop();
        }
    }

    public abstract void setSendPTZCmd(boolean isSend);

    @Override
    public void onPause() {
        super.onPause();
        recordAudioStop();
    }

    private void recordAudioStop(){
        if (btnSpeaking!=null){
            btnSpeaking.stopRecordAudio();
        }
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            deviceFeature = getArguments().getParcelable(EXT_DEVICE_FEATURE);
            mDeviceItem = getArguments().getParcelable(CommonConstants.EXT_DEVICE_ITEM);
        }
        if (mCamera == null&&mDeviceItem!=null){
            mCamera = CameraHub.getInstance().getCamera(mDeviceItem.uuid);
        }
        CameraViewActivity cameraViewActivity = (CameraViewActivity) getActivity();
        if (cameraViewActivity != null) {
            ACCameraPlayerView cameraPlayerView = cameraViewActivity.getPlayerView();
            if (cameraPlayerView!=null){
                cameraPlayerView.setLiveViewShow(true);
            }
        }
        TGLog.i(TAG, "onCreate");
    }

    protected void configurationView(int orientation){
        isLandscape = orientation == Configuration.ORIENTATION_LANDSCAPE;
        if (isLandscape){
            layout.setBackgroundResource(R.color.transparent);
        }else {
            layout.setBackgroundResource(R.color.global_customize_fixed_color_light_gray);
        }
    }
    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        configurationView(newConfig.orientation);
        recordAudioStop();
    }

    public void hideMic(){
        if (!DeviceFeatureHelper.supportSpeaker(deviceFeature)){
            if (relMicPhone !=null){
                relMicPhone.setVisibility(View.GONE);
            }
        }
    }

    public void updateDeviceFeature(DeviceFeature deviceFeature) {
        this.deviceFeature = deviceFeature;
        hideMic();
    }

    public void adjustInfoView(boolean misPhoneShow, boolean controlViewShow, boolean resolutionShow) {
        TGLog.d("controlViewShow = " + controlViewShow);
        boolean showMic = misPhoneShow;
        if (!DeviceFeatureHelper.supportSpeaker(deviceFeature)){
            showMic = false;
        }

        if (isLandscape){
            relMicPhone.setVisibility(View.GONE);
            mPlayerResolutionLayout.setVisibility(resolutionShow ? View.VISIBLE : View.GONE);
        }else {
            if (relMicPhone != null) {
                if (showMic){
                    setSpeakingShow();
                }else{
                    relMicPhone.setVisibility(View.GONE);
                }
            }
        }
    }


    protected void setSpeakingShow(){
        if (DeviceFeatureHelper.supportSpeaker(deviceFeature)){
            boolean supportTalkBack = CameraViewHelper.isTalkback2W(getContext());
            relMicPhone.setVisibility(supportTalkBack?View.GONE:View.VISIBLE);
        }else{
            relMicPhone.setVisibility(View.GONE);
        }
    }

    public void setResolutionInfo(List<String> list){
        if (isLandscape && mPlayerResolutionLayout.getVisibility() == View.VISIBLE){
            TextView uhd = mPlayerResolutionLayout.findViewById(R.id.camera_live_player_resolution_uhd);
            TextView fhd = mPlayerResolutionLayout.findViewById(R.id.camera_live_player_resolution_fhd);
            TextView hd = mPlayerResolutionLayout.findViewById(R.id.camera_live_player_resolution_hd);
            TextView sd = mPlayerResolutionLayout.findViewById(R.id.camera_live_player_resolution_sd);
            uhd.setVisibility(list.contains(uhd.getText().toString()) ? View.VISIBLE : View.GONE);
            fhd.setVisibility(list.contains(fhd.getText().toString()) ? View.VISIBLE : View.GONE);
            hd.setVisibility(list.contains(hd.getText().toString()) ? View.VISIBLE : View.GONE);
            sd.setVisibility(list.contains(sd.getText().toString()) ? View.VISIBLE : View.GONE);
            setTextColor(list, uhd);
            setTextColor(list, fhd);
            setTextColor(list, hd);
            setTextColor(list, sd);
            uhd.setOnClickListener(v -> onSelectResolutionClick(uhd.getText().toString()));
            fhd.setOnClickListener(v -> onSelectResolutionClick(fhd.getText().toString()));
            hd.setOnClickListener(v -> onSelectResolutionClick(hd.getText().toString()));
            sd.setOnClickListener(v -> onSelectResolutionClick(sd.getText().toString()));
        }
    }

    private void setTextColor(List<String> list, TextView uhd) {
        if (list.get(0).equals(uhd.getText().toString())) {
            uhd.setTextColor(getResources().getColor(R.color.message_body_textcolor));
        } else {
            uhd.setTextColor(getResources().getColor(R.color.white));
        }
    }

    private void onSelectResolutionClick(String text){
        Activity activity = getActivity();
        TGApplicationBase.getInstance().putGlobalObject(BottomSheetListDialog.ACTION_RESOLUTION, false);
        if (activity instanceof CameraViewActivity){
            ((CameraViewActivity)activity).onSelectResolutionClick(text);
        }
    }

    public abstract int getPtzControlViewVisible();
    public void setPtzControlViewVisible(boolean show){}
    private void requestAudioPermission() {
        TGLog.d(EXT_DEVICE_FEATURE,"requestAudioPermission");
        XXPermissions.with(getActivity()).permission(Permission.RECORD_AUDIO).request(new OnPermissionCallback() {
            @Override
            public void onGranted(List<String> permissions, boolean all) {
            //权限被允许
                hasAudioPermission = true;
                TGLog.d(EXT_DEVICE_FEATURE,"requestAudioPermission = true");
            }

            @Override
            public void onDenied(List<String> permissions, boolean never) {
                Activity activity = getActivity();
                if (activity != null) {
                    MsgCenterToast.show(activity, R.string.audio_permission_deny);
                }
            }
        });

    }

    @Override
    public void onRecordStart() {
        requestAudioPermission();
        TGLog.d(EXT_DEVICE_FEATURE,"onRecordStart hasAudioPermission = " + hasAudioPermission);
        if (hasAudioPermission) {
            if (recordAudioListener != null) {
                recordAudioListener.onRecordStart();
            }
            if (!isLandscape) {
                if (lightView != null){
                    lightView.setVisibility(View.VISIBLE);
                }
            }
            if (btnSpeaking!=null&&btnSpeaking.isSelected()){
                setBtnSpeakingDown();
            }
        }else{
            if (btnSpeaking!=null){
                btnSpeaking.setSelected(false);
            }
        }

    }

    @Override
    public void onRecordStop() {
        if (hasAudioPermission) {
            if (recordAudioListener != null) {
                recordAudioListener.onRecordStop();
            }
        }
        if (lightView != null){
            lightView.setVisibility(View.GONE);
        }
        if (btnSpeaking!=null){
            btnSpeaking.setSelected(false);
        }
        setBtnSpeakingUp();
    }
    protected void setBtnSpeakingUp(){
        if (recordViewIcon != null) {
            recordViewIcon.setImageResource(R.drawable.ic_tange_global_icon_microphone_gray);
        }
        if (recordViewShadowLayout != null) {
            recordViewShadowLayout.setShadowColor(getResources().getColor(R.color.white_rounded_btn_shadow_color));
        }
    }
    protected void setBtnSpeakingDown(){
        if (recordViewIcon != null) {
            recordViewIcon.setImageResource(R.drawable.ic_tange_global_icon_microphone_white);
        }
        if (recordViewShadowLayout != null) {
            recordViewShadowLayout.setShadowColor(getResources().getColor(R.color.global_customize_fixed_color_shadow));
        }
    }
    protected void setBtnSpeakingOnTouchListener(){
        if (btnSpeaking==null)return;
        btnSpeaking.setOnTouchListener((v, event) -> {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                setBtnSpeakingDown();
            } else if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL || event.getAction() == MotionEvent.ACTION_POINTER_UP) {
                setBtnSpeakingUp();

            } else {
                if (recordViewIcon != null) {
                    recordViewIcon.setImageResource(R.drawable.ic_tange_global_icon_microphone_white);
                }
            }
            return false;
        });
    }
}

